'use strict';
let http = require('http');
let querystring = require('querystring');
let iconv = require('iconv-lite');

let util = {
    // 对http.request的封装
    ajax(params = {}, cb, error) {
        let cpParams = JSON.parse(JSON.stringify(params));
        let opts = {
            protocol: 'http:',
            hostname: 'localhost',
            port: 80,
            path: '/',
            method: 'GET',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            encoding: 'utf8'
        };

        let matchURL;
        let urlReg = /^(https?:)\/\/([\w\.]+)((\/[\w\W]+)$)?/;
        if (cpParams.url) {
            matchURL = cpParams.url.match(urlReg);
        }
        if (matchURL) {
            cpParams.protocol = matchURL[1];
            cpParams.hostname = matchURL[2];
            cpParams.path = matchURL[3] || '/';
        }
        if (!cpParams.hostname || !cpParams.path) {
            console.error('ajax缺少url参数。');
            return;
        }

        cpParams.method = cpParams.method.toUpperCase();

        this.extend(opts, cpParams);

        // 如果回调函数类型不符合，赋值一个空函数
        if (this.getType(cb) !== 'function') {
            cb = function () {};
        }
        if (this.getType(error) !== 'function') {
            error = function () {};
        }

        // 设置请求参数
        let postData = '';
        let dataType = this.getType(cpParams.data);
        switch (dataType) {
            case 'object':
            case 'array':
                postData = querystring.stringify(params.data);
                break;
            case 'string':
            case 'number':
                postData = cpParams.data;
                break;
            case 'undefined':
            case 'null':
                postData = '';
                break;
            default:
                console.error('ajax参数data的类型只能是 object(只有一层结构),array,string,number。');
                return;
        }
        if (opts.method === 'GET') {
            opts.path += '?' + postData;
        }
        const req = http.request(opts, (res) => {
            let data = '';
            //   res.setEncoding('utf8');
            let chunks = [];
            res.on('data', (chunk) => {
                // data += chunk;
                chunks.push(chunk);
            });
            res.on('end', () => {
                cb({
                    statusCode: res.statusCode,
                    headers: res.headers,
                    data: iconv.decode(Buffer.concat(chunks), opts.encoding)
                })
            });
        });

        req.setHeader('Content-Length', Buffer.byteLength(postData));

        req.on('error', (e) => {
            error(e);
        });

        // 写入数据到请求主体
        if (opts.method !== 'GET') {
            req.write(postData);
        }
        req.end();
    },
    // 
    extend(target, src) {
        let keyType;
        for (let key in src) {
            keyType = this.getType(src[key]);
            if (keyType === 'object') {
                if (!target[key]) {
                    target[key] = src[key];
                } else {
                    this.extend(target[key], src[key]);
                }
            } else {
                target[key] = src[key];
            }
        }
    },
    // 获取变量类型
    getType(variety) {
        let toString = Object.prototype.toString;
        let map = {
            '[object Boolean]': 'boolean',
            '[object Number]': 'number',
            '[object String]': 'string',
            '[object Function]': 'function',
            '[object Array]': 'array',
            '[object Date]': 'date',
            '[object RegExp]': 'regExp',
            '[object Undefined]': 'undefined',
            '[object Null]': 'null',
            '[object Object]': 'object'
        }
        if (typeof window !== 'undefined') {
            if (variety instanceof Element) {
                return 'Element';
            }
        }
        return map[toString.call(variety)];
    },
}

module.exports = util;